<script setup lang="ts">
	import { ref, reactive, unref } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { route } from '@/uni_modules/uview-plus'
	import { storeList, storeEdit } from '@/package_saleman/api/Home'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	import { useUserStore } from '@/stores/user'

	const { userInfo } = useUserStore()
	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)
	const orderColumns1 = reactive([
		{
			label: '上次金额',
			field: 'last_amount'
		},
		{
			label: '欠款金额',
			field: 'debt_amount'
		},
		{
			label: '总下单额',
			field: 'total_amount'
		}
	])

	const orderColumns2 = reactive([
		{
			label: '欠款单数',
			field: 'debt_order_num'
		},
		{
			label: '总下单数',
			field: 'total_order_num'
		},
		{
			label: '账期时间',
			field: 'due_time'
		}
	])

	const navigationColumns = reactive([
		// {
		// 	label: '下单',
		// 	icon: '/static/icon/icon2.png',
		// },
		// {
		// 	label: '退货',
		// 	icon: '/static/icon/icon3.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '换货',
		// 	icon: '/static/icon/icon4.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '陈列',
		// 	icon: '/static/icon/icon5.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '收款',
		// 	icon: '/static/icon/icon6.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '往来',
		// 	icon: '/static/icon/icon7.png',
		// 	pagePath: ''
		// },
		// {
		// 	label: '查账',
		// 	icon: '/static/icon/icon8.png',
		// 	pagePath: ''
		// },
		{
			label: '日志',
			icon: '/static/icon/icon6.png',
			pagePath: '/package_tools/pages/Store/auxiliaryTools/signLog'
		}
	])
	const formData = ref(null)
	function deepClone(obj : any) {
		if (typeof obj !== 'object' || obj === null) {
			return obj;
		}

		let clone;
		if (Array.isArray(obj)) {
			clone = [];
			for (let i = 0; i < obj.length; i++) {
				clone[i] = deepClone(obj[i]);
			}
		} else {
			clone = {};
			for (const key in obj) {
				if (obj.hasOwnProperty(key)) {
					clone[key] = deepClone(obj[key]);
				}
			}
		}

		return clone;
	}
	const useStoreDetail = () => {
		const storeInfo = ref({})
		const getStoreInfo = async (id : string) => {
			const params = {
				id
			}
			try {
				const res = await storeList(params)
				storeInfo.value = res.data
				formData.value = deepClone(storeInfo.value);
				// if (res.data && res.data.store_img) {
				// 	const firstImage = res.data.store_img.split(',')[0];
				// 	storeInfo.value.firstImage = firstImage;
				// }
				if (storeInfo.value?.store_img) {
					fileList1.value = storeInfo.value?.store_img.split(",").map((val) => ({
						url: val
					}))
				} else {
					// 如果不存在，则设置 fileList1.value 为一个空数组
					fileList1.value = [];
				}
			} catch (err) {
				console.log(err);
			}
		}

		return {
			storeInfo,
			getStoreInfo
		}
	}
	const { storeInfo, getStoreInfo } = useStoreDetail()
	const store_id = ref('')
	onLoad((options) => {
		const { id } = options as { id : string }
		// is_sign.value = options.is_sign
		store_id.value = id
	})
	onShow(() => {
		getStoreInfo(store_id.value)
	})
	// 导航
	const openLocation = () => {
		uni.openLocation({
			latitude: Number(unref(storeInfo).lat),
			longitude: Number(unref(storeInfo).lon),
			name: unref(storeInfo).address,
			success: () => {
				console.log('success');
			},
			fail(err) {
				console.log(err)
			}
		})
	}

	// 电话
	const callStore = () => {
		uni.makePhoneCall({
			phoneNumber: unref(storeInfo).phone
		})
	}

	// const toPage = (url : string) => {
	// 	if (url)
	// 		route({
	// 			url,
	// 			params: {
	// 				network_id: storeInfo.value.id,
	// 				store_name: storeInfo.value?.store_name
	// 			},
	// 		})
	// }
	//签到
	// const showSign = ref(false)
	// const is_sign = ref("1")
	// const remark = ref('')
	// const confirmSign = async () => {
	// 	const { id, lon, lat } = storeInfo.value;
	// 	const param = {
	// 		store_id: id,
	// 		lon,
	// 		lat,
	// 		remark: remark.value
	// 	}
	// 	const res = await storeSign(param)
	// 	if (res.code === 200) {
	// 		is_sign.value = "2"
	// 		showSign.value = false
	// 		showNotify({
	// 			type: 'success',
	// 			message: res.msg
	// 		})
	// 	}


	// }

	// 修改门店信息
	const toStoreEdit = () => {
		addShow.value = true
		// route({
		// 	url: '/package_saleman/pages/Store/editStore',
		// 	params: {
		// 		storeInfo: JSON.stringify(storeInfo.value)
		// 	}
		// })
	}
	const addShow = ref(false)

	// 使用 ref 创建响应式引用  
	const formRef = ref(null);
	const useUploadImg = () => {
		const fileList1 = ref<any[]>([])
		// 添加图片
		type UploadImageFile = {
			size : number,
			type : 'image',
			url : string,
			thumb : string
		}
		type UploadImageParams = {
			file : UploadImageFile | UploadImageFile[],
			index : number,
			name : string
		}
		type AddImage = (event : UploadImageParams) => any
		// 新增图片
		const addImage = async (event) => {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = fileList1.value.length;
			lists.map((item) => {
				fileList1.value.push({
					...item,
					status: 'uploading',
					message: '上传中',
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await uploadImage(lists[i].url);
				let item = fileList1.value[fileListLen];
				fileList1.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result,
				});
				fileListLen++;
			}
		};

		const uploadImage = (url) => {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: `${process.env.VUE_APP_BASE_URL}/salesman/upload`,
					filePath: url,
					name: 'file',
					header: {
						'content-type': 'application/json;charset=utf-8',
						'token': uni.getStorageSync('trioToken'),
					},
					success: (res) => {
						const data = JSON.parse(res.data)
						if (data.code !== 200) {
							uni.showToast({
								title: `${data.msg},请重新上传!`,
								icon: 'none'
							})
							return
						}
						setTimeout(() => {
							resolve(data.data.url);
						}, 1000);
					},
				});
			});
		};
		// 删除图片
		const delImage = (event : UploadImageParams) => {
			fileList1.value.splice(event.index, 1)
		}

		return {
			fileList1,
			addImage,
			delImage,
			uploadImage
		}
	}
	const { fileList1, addImage, delImage } = useUploadImg()
	// 选择地址
	const setAddress = () => {
		uni.chooseLocation({
			success: (res) => {
				if (res) {
					formData.value.address = `${res.address}${res.name}`
					formData.value.lon = res.longitude
					formData.value.lat = res.latitude
				}
			},
			fail: (err) => {
				console.log(err);
			}
		})
	}

	const submitLoading = ref(false)
	const submit = async () => {
		if (fileList1.value.length > 0) {
			formData.value.store_img = fileList1.value.map((item) => item.url).join(',')
		}
		formRef.value.validate().then(async () => {
			try {
				submitLoading.value = true
				const res = await storeEdit(formData.value)
				showNotify({
					type: 'success',
					message: res.msg,
					top: 0
				})
				formRef.value.resetFields()
				fileList1.value = []
				addShow.value = false
				getStoreInfo(store_id.value)
				// route({
				// 	type: 'navigateBack'
				// })
			} catch (error) {
				showNotify({
					type: 'error',
					message: error.msg,
					top: 0
				})
			} finally {
				submitLoading.value = false
			}
		})

	}
	const rules = reactive({
		'store_name': {
			type: 'string',
			required: true,
			message: '请填写门店名称',
			trigger: ['blur', 'change'],
		},
		'contacts': {
			type: 'string',
			required: true,
			message: '请填写门店联系人',
			trigger: ['blur', 'change'],
		},
		'phone': {
			type: 'string',
			required: true,
			message: '请填写门店联系电话',
			trigger: ['blur', 'change'],
		},
		'address': {
			type: 'string',
			required: true,
			message: '请填写门店地址',
			trigger: ['blur', 'change'],
		}
	})
</script>
<template>
	<view class="content">
		<up-navbar :title="storeInfo?.store_name" placeholder autoBack></up-navbar>
		<view class="store-info">
			<up-upload :fileList="fileList1" @afterRead="addImage" @delete="delImage" multiple :maxCount="1"
				:previewFullImage="true"></up-upload>
			<!-- <up-avatar :src="storeInfo.firstImage" size="200rpx" shape="square"></up-avatar> -->
			<view class="info">
				<view class="line">
					<view>
						<text class="line-name">{{storeInfo?.store_name}}</text>
						<text
							style="font-size: 24rpx;font-weight: 500;color: rgba(156, 154, 161, 1);">{{storeInfo.last_date}}</text>
					</view>
					<view v-if="userInfo.scene_id == 2"><up-button @click="toStoreEdit" type="primary"
							size="mini">修改门店信息</up-button></view>
				</view>
				<view class="address" style="margin-top: 30rpx;">
					<text>店主：</text>
					<text style="color: rgba(45, 45, 46, 1);">{{storeInfo.contacts}}</text>
				</view>
				<view class="address" style="margin-top: 10rpx;">
					<text>电话：</text>
					<text style="color: rgba(45, 45, 46, 1);">{{storeInfo.phone}}</text>
				</view>
				<view class="address">
					<text>地址：</text>
					<text style="color: rgba(45, 45, 46, 1);">{{storeInfo.address}}</text>
				</view>
			</view>
		</view>

		<view class="order-info">
			<up-grid :border="false">
				<up-grid-item v-for="item in orderColumns1" :key="item.field" :customStyle="{ margin: '20rpx 0' }">
					<text class="label">{{item.label}}</text>
					<text class="value">{{ storeInfo[item.field] || '暂无' }}</text>
				</up-grid-item>
			</up-grid>
			<up-line color="#FFFFFF"></up-line>
			<up-grid :border="false">
				<up-grid-item v-for="item in orderColumns2" :key="item.field" :customStyle="{ margin: '20rpx 0' }">
					<text class="label">{{item.label}}</text>
					<text class="value">{{ storeInfo[item.field] || '暂无' }}</text>
				</up-grid-item>
			</up-grid>
		</view>
		<!-- <view style="margin-top: 100rpx;">
			<view style="font-size: 16px;font-weight: 700;color: rgba(2, 14, 36, 1);margin-left: 30rpx;">辅助工具</view>
			<up-grid :border="false" col="5">
				<up-grid-item v-for="item in navigationColumns" :key="item.pagePath" :name="item.pagePath"
					@click=toPage(item.pagePath) :customStyle="{ margin: '40rpx 0 50rpx 0' }">
					<up-icon :name="item.icon" :label="item.label" labelPos="bottom" labelSize="28rpx" space="20rpx"
						width="60rpx" height="60rpx">
					</up-icon>
				</up-grid-item>
			</up-grid>
		</view> -->

		<view class="bottom-area">
			<view class="line">
				<view class="item">
					<up-icon name="/static/icon/icon9.png" label="电话" labelSize="28rpx" space="20rpx" width="44rpx"
						height="44rpx" @click="callStore">
					</up-icon>
				</view>
				<view class="item">
					<up-icon name="/static/icon/icon10.png" label="导航" labelSize="28rpx" space="20rpx" width="44rpx"
						height="44rpx" @click="openLocation">
					</up-icon>
				</view>
			</view>
			<!-- <view class="line" v-if="userInfo.scene_id == 2">
				<up-button class="up-reset-button" size="large" shape="circle" icon="map" color="rgba(55, 131, 252, 1)"
					:disabled="is_sign === '1' ? false : true" iconColor="#FFFFFF"
					@click="showSign = true">{{ is_sign === "1" ? '签到' : '已签到'}}</up-button>
			</view>
			<view class="line" v-else>
				<up-button class="up-reset-button" size="large" shape="circle" icon="map" color="rgba(55, 131, 252, 1)"
					iconColor="#FFFFFF">签到</up-button>
			</view> -->
		</view>
		<!-- <up-modal :show="showSign" @confirm="confirmSign" @cancel="showSign = false" ref="uModal" :asyncClose="true"
			buttonReverse title="是否以当前位置进行签到?" showCancelButton>
			<view style="width: 90%;">
				<up-textarea v-model="remark" placeholder="请输入备注 (选填)" count autoHeight></up-textarea>
			</view>
		</up-modal> -->
		<up-notify ref="NotifyRef"></up-notify>
	</view>
	<up-popup v-model:show="addShow" mode="bottom" :round="10" :customStyle="{height: '75vh',padding: '36rpx'}">
		<view style="text-align: center; font-size: 32rpx; font-weight: bold; margin-bottom: 10rpx;">修改门店</view>
		<view style="padding: 0 32rpx;">
			<up-form labelPosition="left" labelWidth="75" :model="formData" :rules="rules" ref="formRef">
				<up-form-item label="门店名称" prop="store_name" borderBottom required>
					<up-input v-model="formData.store_name" border="none" placeholder="请填写门店名称"></up-input>
				</up-form-item>
				<up-form-item label="门店简称" prop="store_short_name" borderBottom>
					<up-input v-model="formData.store_short_name" border="none" placeholder="请填写门店简称"></up-input>
				</up-form-item>
				<up-form-item label="联系人" prop="contacts" borderBottom required>
					<up-input v-model="formData.contacts" border="none" placeholder="请填写门店联系人"></up-input>
				</up-form-item>
				<up-form-item label="联系电话" prop="phone" borderBottom required>
					<up-input v-model="formData.phone" border="none" placeholder="请填写门店联系电话"></up-input>
				</up-form-item>
				<up-form-item label="地址" prop="address" borderBottom required @click="setAddress">
					<!-- <up-input v-model="formData.address" border="none" placeholder="点击选择门店地址" readonly type ="textarea" ></up-input> -->
					<view class="">
						{{formData.address}}
					</view>
				</up-form-item>
				<up-form-item label="店面图片" prop="store_img" borderBottom>
					<up-upload :fileList="fileList1" :previewFullImage="true" maxCount="3" @afterRead="addImage"
						@delete="delImage" multiple></up-upload>
				</up-form-item>
			</up-form>
			<up-button @click="submit" type="primary" :loading="submitLoading" :disabled="submitLoading">提交</up-button>
			<up-notify ref="NotifyRef"></up-notify>
		</view>
	</up-popup>
</template>

<style scoped lang="scss">
	.content {
		width: 100%;
		padding: 20rpx;
		box-sizing: border-box;

		.store-info {
			display: flex;
			align-items: center;
			gap: 20rpx;
			margin-bottom: 40rpx;


			.info {
				width: 100%;
				height: 200rpx;

				.line {
					width: 100%;
					display: flex;
					justify-content: space-between;
					margin-bottom: 10rpx;
					font-size: 24rpx;

					.line-name {
						font-size: 28rpx;
						font-weight: 700;
						color: rgba(35, 35, 36, 1);
						margin-right: 20rpx;
					}

					.header-right {
						display: flex;

						.right-img {
							width: 34rpx;
							height: 34rpx;
							vertical-align: middle;
							margin-right: 20rpx;
						}

						.right-name {
							font-size: 28rpx;
							font-weight: 700;
							color: rgba(55, 131, 252, 1);
						}
					}
				}



				.address {
					font-size: 24rpx;
					color: rgba(156, 154, 161, 1);
				}
			}
		}

		.order-info {
			width: 100%;
			border-radius: 20rpx;
			background: linear-gradient(180deg, rgba(242, 243, 245, 1) 0%, rgba(242, 243, 245, 0) 100%);

			.label {
				font-size: 24rpx;
				color: rgba(156, 154, 161, 1);
				margin: 10rpx 0;
			}

			.value {
				font-size: 28rpx;
			}
		}


		.bottom-area {
			position: fixed;
			bottom: 0;
			left: 0;
			display: flex;
			flex-direction: column;
			gap: 40rpx;
			width: 100%;
			padding: 0 40rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			/* 兼容iOS < 11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS 11.2及以上 */
			box-sizing: border-box;

			.line {
				display: flex;
				justify-content: space-between;

				.item {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 232rpx;
					height: 80rpx;
					border-radius: 40rpx;
					background: rgba(245, 245, 245, 1);
				}
			}
		}

	}
</style>